package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.basicinfo.DeviceTypeMapper;
import com.ruikong.dazhi.entity.basicinfo.*;
import com.ruikong.dazhi.dao.basicinfo.DeviceMapper;
import com.ruikong.dazhi.entity.basicinfo.Device;
import com.ruikong.dazhi.model.input.DevicePageInput;
import com.ruikong.dazhi.service.basicinfo.IDeviceService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * (Device)表服务实现类
 *
 * @author HuaJiaYi
 * @since 2021-09-29 10:55:42
 */
@Service("deviceService")
public class DeviceServiceImpl implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;

    @Override
    public Device queryById(Integer id) {
        return this.deviceMapper.queryById(id);
    }

    @Override
    public int insert(Device device) {
        return this.deviceMapper.insert(device);
    }

    @Override
    public int update(Device device) {
        return this.deviceMapper.update(device);
    }

    @Override
    public int deleteById(Integer id) {
        return this.deviceMapper.deleteById(id);
    }

    @Override
    public PageInfo<Device> getDevicePageList(DevicePageInput input) {
        PageHelper.startPage(input.getPageNumber(), input.getPageSize());
        List<Device> deviceList = this.deviceMapper.getDevicePageList(input);
        PageInfo<Device> pageInfo = new PageInfo<>(deviceList);
        return pageInfo;
    }

    @Override
    public Integer isExist(Device device) {
        return this.deviceMapper.isExist(device);
    }

    //Excel
    @Override
    public BaseResult deviceImport(MultipartFile multipartFile, Integer personnelId) {
        BaseResult baseResult = new BaseResult();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }
                //设备
                Device deivce = new Device();
                //初始化原料——未删除
                deivce.setIsDeleted(0);
                //设备编号
                cell = row.getCell(0);
                String deviceSn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，设备编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    deviceSn = cell.getStringCellValue().trim();
                    if (deviceMapper.isDeviceSnExist(deviceSn) > 0) {
                        baseResult.setMsg(String.format("错误！表格第%s行，设备编号已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        deivce.setDeviceSn(deviceSn);
                    }
                }
                //设备名称
                cell = row.getCell(1);
                String deviceName;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，设备名称不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    deviceName = cell.getStringCellValue().trim();
                    deivce.setDeviceName(deviceName);
                }
                //设备类型
                cell = row.getCell(2);
                String deviceTypeName;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，原料类型不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    deviceTypeName = cell.getStringCellValue().trim();
                    DeviceType deviceType = this.deviceTypeMapper.queryDeviceTypeByName(deviceTypeName);
                    if (deviceType == null) {
                        baseResult.setMsg(String.format("错误！表格第%s行，设备类型不存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    } else {
                        deivce.setDeviceTypeId(deviceType.getDeviceTypeId());
                    }
                }
                //规格型号
                cell = row.getCell(3);
                String model;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，规格型号不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    model = cell.getStringCellValue().trim();
                    deivce.setModel(model);
                }
                //保养周期（天数）
                cell = row.getCell(4);
                String maintenanceCycle;
//                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
//                    baseResult.setMsg(String.format("错误！表格第%s行，保养周期（天数）不能为空", index + 1));
//                    baseResult.setCode(ResultApi.failCode);
//                    file.delete();
//                    return baseResult;
//                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    maintenanceCycle = cell.getStringCellValue().trim();
                    deivce.setMaintenanceCycle(maintenanceCycle);
                }
                //供应商
                cell = row.getCell(5);
                String supplier;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    supplier = cell.getStringCellValue();
                    deivce.setSupplier(supplier);
                } else {
                    deivce.setSupplier("");
                }
                //购买时间
                cell = row.getCell(6);
                Date buyDate;
                if (cell != null) {
                    buyDate = cell.getDateCellValue();
                    deivce.setBuyDate(buyDate);
                } else {
                    deivce.setBuyDate(null);
                }
                //安装时间
                cell = row.getCell(7);
                Date installDate;
                if (cell != null) {
                    installDate = cell.getDateCellValue();
                    deivce.setInstallDate(installDate);
                } else {
                    deivce.setInstallDate(null);
                }
                //投产时间
                cell = row.getCell(8);
                Date commissioningDate;
                if (cell != null) {
                    commissioningDate = cell.getDateCellValue();
                    deivce.setCommissioningDate(commissioningDate);
                } else {
                    deivce.setCommissioningDate(null);
                }
                //创建时间
                cell = row.getCell(9);
                Date createTime;
                if (cell != null) {

                    createTime = cell.getDateCellValue();
                    deivce.setCreateTime(createTime);
                } else {
                    //创建时间不填
                    //以当前时间为准
                    deivce.setCreateTime(new Date());
                }
                //备注
                cell = row.getCell(8);
                String remarks;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    remarks = cell.getStringCellValue().trim();
                    deivce.setRemarks(remarks);
                }

                //id
                deivce.setId(deviceMapper.getId() + 1);
                //创建人
                deivce.setUserId(personnelId);
                this.deviceMapper.insert(deivce);
                index++;
            }

            file.delete();
            baseResult.setMsg("导入成功");
        } catch (Exception e) {
            baseResult.setCode(ResultApi.errorCode);
            baseResult.setMsg("设备导入时出错");
            e.printStackTrace();
        }
        return baseResult;
    }

    @Override
    public boolean deleteByIds(Integer[] ids) {
        return false;
    }


}
